from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.template.defaulttags import register
from django import template

from django.http import HttpResponse, JsonResponse


@register.filter(name='mul')
def multiply(value, arg):
    return float(value) * float(arg)


def cashier(request):
    from .models import ProductCategory, Product
    
    categories = ProductCategory.objects.all()
    products = Product.objects.filter(stock__gt=0)
    
    # Handle search queries
    search_term = request.GET.get('search', '')
    if search_term:
        products = products.filter(
            Q(goods_name__icontains=search_term) |
            Q(goods_code__icontains=search_term)
        )
    
    cart_items = []
    total = 0
    
    if 'cart' in request.session:
        cart = request.session['cart']
        for product_id, quantity in cart.items():
            try:
                product = Product.objects.get(id=product_id)
                item_total = product.price * quantity
                cart_items.append({
                    'product': product,
                    'quantity': quantity,
                    'item_total': item_total
                })
                total += item_total
            except Product.DoesNotExist:
                continue
    
    return render(request, 'cashier.html', {
        'categories': categories,
        'products': products,
        'cart_items': cart_items,
        'total_price': total
    })

def get_cart_items(request):
    cart_items = []
    total = 0
    
    if 'cart' in request.session:
        cart = request.session['cart']
        for Product_id, quantity in cart.items():
            try:
                Product = Product.objects.get(id=Product_id)
                item_total = Product.Product_price * quantity
                cart_items.append({
                    'Product': Product,
                    'quantity': quantity,
                    'item_total': item_total
                })
                total += item_total
            except Product.DoesNotExist:
                continue
    
    return JsonResponse({
        'cart_items': [{
            'Product': {
                'Product_name': item['Product'].Product_name,
                'Product_price': float(item['Product'].Product_price)
            },
            'quantity': item['quantity'],
            'item_total': float(item['item_total'])
        } for item in cart_items],
        'total': float(total)
    })


def checkout(request):
    if not request.user.is_authenticated:
        return redirect('login')
        
    if 'cart' not in request.session or not request.session['cart']:
        return redirect('cashier')
    
    # Process payment and create order
    try:
        # Get cart items
        cart = request.session['cart']
        cart_items = []
        total_price = 0
        
        for Product_id, quantity in cart.items():
            Product = ProductInfo.objects.get(id=Product_id)
            item_total = Product.Product_price * quantity
            cart_items.append({
                'Product': Product,
                'quantity': quantity,
                'item_total': item_total
            })
            total_price += item_total
        
        # Clear cart after successful checkout
        request.session['cart'] = {}
        request.session.modified = True
        
        return render(request, 'checkout.html', {
            'cart_items': cart_items,
            'total_price': total_price
        })
    except Exception as e:
        return JsonResponse({'status': 0, 'errmsg': str(e)})


def add_to_cart_cashier(request):
    """
    Add Product to shopping cart (cashier version)
    """
    if request.method == 'GET':
        Product_id = request.GET.get('product_id') or request.GET.get('id')
        quantity = int(request.GET.get('quantity', 1))
    elif request.method == 'POST':
        Product_id = request.POST.get('product_id') or request.POST.get('id')
        quantity = int(request.POST.get('quantity', 1))
    else:
        return JsonResponse({'status': 0, 'errmsg': 'Invalid request method'}, status=400)
    
#     if not Product_id:
#         return JsonResponse({'status': 0, 'errmsg': '商品ID不能为空'}, status=400)
    
#     try:
#         Product = Product.objects.get(id=Product_id)
#     except Product.DoesNotExist:
#         return JsonResponse({'status': 0, 'errmsg': '商品不存在'}, status=404)
    
#     # Initialize cart in session if not exists
#     if 'cart' not in request.session:
#         request.session['cart'] = {}
    
#     cart = request.session['cart']
    
#     # Add or update Product in cart
#     if Product_id in cart:
#         cart[Product_id] += quantity
#     else:
#         cart[Product_id] = quantity
    
#     # Save cart to session
#     request.session.modified = True
    
#     return JsonResponse({'status': 1, 'msg': '添加成功'})

# def add_cart(request):
#     """
#     View to handle adding items to shopping cart
#     """
    Product_id = request.GET.get('id')
    quantity = int(request.GET.get('quantity', 1))
    
    if not Product_id:
        return HttpResponse('商品ID不能为空', status=400)
    
    try:
        Product = ProductInfo.objects.get(id=Product_id)
    except ProductInfo.DoesNotExist:
        return HttpResponse('商品不存在', status=404)
    
    # Initialize cart in session if not exists
    if 'cart' not in request.session:
        request.session['cart'] = {}
    
    # Update cart quantity
    cart = request.session['cart']
    cart[Product_id] = cart.get(Product_id, 0) + quantity
    request.session.modified = True
    
    return JsonResponse({'status': 1, 'msg': '商品已添加到购物车'})